package com.itheima.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

/*
 * 拦截器统一处理token
 * */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token数据
        String token = request.getHeader("Authorization");
        //2.判断token是否为空
        if (StrUtil.isEmpty(token)) {
            //设置状态码为401,标识权限不足
            response.setStatus(401);
            return false;
        }
        //判断token是否过期,从redis中读取token
        Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
        if (!flag) {
            response.setStatus(401);
            return false;
        }
        //解析token
        Map map = JwtUtil.parseToken(token);
        //将token解析为user对象
        User user = BeanUtil.mapToBean(map, User.class, true);
        //user解析错误
        if (user == null) {
            response.setStatus(401);
            return false;
        }
        //此次操作 token有效
        UserHolder.set(user);
        //续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, "1", Duration.ofDays(7));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束之后,将数据清除
        UserHolder.remove();
    }
}
